<template>
  <div>
    <h1>Todo Show</h1>
    <template v-if="!isEdit">
      <h2>{{todo.content || '加载中'}}</h2>
      <div v-html="todo.description"></div>
    </template>
    <template v-else>
      <el-form ref="form" label-width="80px">
        <el-form-item label="标题">
          <el-input v-model="todo.content"></el-input>
        </el-form-item>
        <quill-editor
          :content="todo.description"
          @change="onEditorChange($event)"
        />
      </el-form>
    </template>

    <div>
      <button @click="isEditAble">
        {{updateBtnText}}
      </button>
      <button @click="deleteItem">删除</button>
    </div>
  </div>
</template>

<script>
import axios from 'axios'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { quillEditor } from 'vue-quill-editor'

export default {
  name: "TodoShow",
  components: {quillEditor},
  data() {
    return {
      id: null,
      todo: {},
      isEdit: false,
      content: '<h2>I am Example</h2>',
      editorOption: {
      }
    }
  },
  computed: {
    updateBtnText() {
      return this.isEdit ? '保存' : '修改'
    }
  },
  created() {
    this.id = this.$route.params.id
    axios({
      url: `http://localhost:3000/todos/${this.id}`
    }).then((res) => {
      this.todo = res.data
      console.log(res)
    })
  },
  methods: {
    onEditorChange({html, text }) {
      // console.log(html)
      // console.log('=========')
      console.log(text)
      this.content = html
      this.todo.description = html
    },
    isEditAble() {
      if (!this.isEdit) {
        this.isEdit = true
      } else {
        axios({
          method: 'PUT',
          url: `http://localhost:3000/todos/${this.id}`,
          data: {
            content: this.todo.content,
            description: this.todo.description,
          }
        }).then(() => {
          this.isEdit = false
        })
      }
    },
    deleteItem() {
      this.$confirm('此操作将永久删除数据, 是否继续?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        axios({
          method: 'DELETE',
          url: `http://localhost:3000/todos/${this.id}`
        }).then(() => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          this.$router.replace({
            name: 'todo'
          })
        }).catch(() => {
          this.$message({
            type: 'error',
            message: '网络错误!'
          });
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    }
  }
}
</script>

<style scoped>

</style>